package top.guxx.springframework.beans.factory.support;

import top.guxx.springframework.beans.BeansException;
import top.guxx.springframework.beans.factory.BeanFactory;
import top.guxx.springframework.beans.factory.config.BeanDefinition;

/**
 * @Author：Guxx
 * @Description：
 * @Date：2024/6/8 21:24
 * @Filename：AbstractBeanFactory
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory  {
    @Override
    public Object getBean(String beanName, Object... args) throws BeansException{
        return doGetBean(beanName,args);
    }

    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name,null);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {

    }
    protected <T> T doGetBean(final String beanName, final  Object[] args){
        Object bean = getSingleton(beanName);
        if (bean != null){
            return (T)bean;
        }
        BeanDefinition beanDefinition = getBeanDefinition(beanName);
        return (T) createBean(beanName, beanDefinition, args);
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object... args) throws BeansException;
}
